home *** CD-ROM | disk | FTP | other *** search
- LISTING 4 -
- /* recurse.c: Illustrate recursion and storage duration */
-
- #include <stdio.h>
-
- main()
- {
- long n;
- long fac(long);
-
- fputs("Enter a small integer: ",stderr);
- scanf("%ld%*c",&n);
- printf("\n%ld! = %ld\n",n,fac(n));
- return 0;
- }
-
- long fac(long n)
- {
- static int depth = 0;
- auto long result;
- void print_current(int,long);
-
- print_current(++depth,n);
- result = (n <= 1) ? 1 : n * fac(n-1);
- print_current(depth--,result);
-
- return result;
- }
-
- void print_current(int depth, long n)
- {
- int i;
-
- /* Indent to show depth */
- for (i = 0; i < depth; ++i)
- fputs(" ",stdout);
-
- printf("%ld\n",n);
- }
-
- /* Output:
- Enter a small integer: 3
- 3
- 2
- 1
- 1
- 2
- 6
-
- 3! = 6
- */
-